package com.d3works.csv.script;

import com.d3works.apps.account.db.Account;
import com.d3works.apps.account.service.AccountService;
import com.d3works.apps.account.service.config.AccountConfigService;
import com.d3works.exception.D3worksException;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import java.util.Map;

public class ImportAccount {

  private static ThreadLocal<Integer> lineNo = new ThreadLocal<>();

  public Object importAccount(Object bean, Map<String, Object> values) {
    Integer line = lineNo.get();

    if (line == null) {
      lineNo.set(1);
      line = 1;
    } else {
      lineNo.set(line + 1);
    }

    if (bean == null) {
      return null;
    }
    assert bean instanceof Account;
    Account account = (Account) bean;

    try {
      if (account.getCompany() != null
          && Beans.get(AccountConfigService.class)
              .getAccountConfig(account.getCompany())
              .getHasAccountCodeFixedNbrChar()) {
        account = Beans.get(AccountService.class).fillAccountCodeOnImport(account, line);
      }
    } catch (D3worksException e) {
      TraceBackService.trace(e);
    }
    return account;
  }

  public void resetLineNo(Map<String, Object> values) {
    lineNo.set(1);
  }
}
